import 'dart:async';
import 'dart:convert';

import 'package:dio/dio.dart' as Resp;
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:ty_smart_watch/bean/login_bean.dart';
import 'package:ty_smart_watch/bean/sms_code_bean.dart';
import 'package:ty_smart_watch/common/common.dart';
import 'package:ty_smart_watch/common/images_url.dart';
import 'package:ty_smart_watch/route/routes.dart';
import 'package:ty_smart_watch/utils/Log.dart';
import 'package:ty_smart_watch/utils/http_util.dart';

/// 用户登录页
class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  bool _clearPhoneVisible = false;
  final TextEditingController _phoneTextController = TextEditingController();
  final TextEditingController _codeTextController = TextEditingController();
  bool _isCodeButtonDisabled = false;
  bool _checked = false;
  bool _loginEnable = false;
  late Timer _codeCountdownTimer;
  int _codeCountdownSeconds = 60;

  @override
  Widget build(BuildContext context) {
    double iconSize = 46;
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: AppBar(
        automaticallyImplyLeading: false,
      ),
      body: Container(
        margin: const EdgeInsets.symmetric(horizontal: 20),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // const Text("欢迎使用LightThings应用", style: TextStyle(color: Color(0xFF0E4298))),
            RichText(
              text: const TextSpan(children: [
                TextSpan(text: "欢迎使用", style: TextStyle(fontSize: 20, color: Color(0xFF0E4298))),
                TextSpan(
                    text: "Lightthings",
                    style: TextStyle(
                        fontSize: 20, color: Color(0xFF0E4298), fontWeight: FontWeight.bold)),
                TextSpan(text: "应用", style: TextStyle(fontSize: 20, color: Color(0xFF0E4298))),
              ]),
            ),
            const Text("与您一起智能生活，健康运动...",
                style: TextStyle(fontSize: 18, color: Color(0xFF0E4298))),
            const SizedBox(height: 24),
            const Text(
              "登录",
              style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold, color: Color(0xFF0C0C0C)),
            ),
            const SizedBox(height: 20),
            Container(
              decoration: BoxDecoration(
                border: Border.all(color: const Color(0xFF7A7A7A), width: 1),
                //圆角半径
                borderRadius: const BorderRadius.all(Radius.circular(50.0)),
                //背景色
                color: const Color(0xFFFFFBFF),
              ),
              child: Row(
                // crossAxisAlignment: CrossAxisAlignment.stretch,
                children: [
                  Expanded(
                    child: Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 10.0),
                      child: TextField(
                        decoration: const InputDecoration(
                            hintText: "请输入手机号",
                            hintStyle: TextStyle(
                              color: Color(0xFF969696),
                            ),
                            border: InputBorder.none),
                        keyboardType: TextInputType.number,
                        inputFormatters: [
                          FilteringTextInputFormatter.digitsOnly, //数字，只能是整数
                        ],
                        controller: _phoneTextController,
                        onEditingComplete: () {
                          Log.d("电话号码编辑完成");
                        },
                        onChanged: (v) {
                          print("输入的内容是 $v  >>  ${v.isNotEmpty}");
                          setState(() {
                            _clearPhoneVisible = v.isNotEmpty;
                          });
                          _checkRegisterEnable();
                        },
                        onSubmitted: (v) {
                          Log.d("电话号码提交完成 $v");
                        },
                        maxLines: 1,
                      ),
                    ),
                  ),
                  Visibility(
                    visible: _clearPhoneVisible,
                    child: GestureDetector(
                      onTap: () {
                        _phoneTextController.clear();
                        setState(() {
                          _clearPhoneVisible = false;
                        });
                      },
                      child: Image.asset(
                        ICON_CLEAR_PHONE_NUMBER,
                        width: 16,
                        height: 16,
                      ),
                    ),
                  ),
                  const SizedBox(width: 6),
                  Container(
                    height: 24,
                    width: 0.5, // 设置竖线的宽度
                    color: const Color(0xFF969696), // 设置竖线的颜色
                  ),
                  const SizedBox(width: 6),
                  const Text(
                    "国家/地区",
                    style: TextStyle(
                      color: Color(0xFF969696),
                    ),
                  ),
                  const SizedBox(width: 10)
                ],
              ),
            ),
            const SizedBox(height: 20),
            Container(
              decoration: BoxDecoration(
                border: Border.all(color: const Color(0xFF7A7A7A), width: 1),
                //圆角半径
                borderRadius: const BorderRadius.all(Radius.circular(50.0)),
                //背景色
                color: const Color(0xFFFFFBFF),
              ),
              child: Row(
                // crossAxisAlignment: CrossAxisAlignment.stretch,
                children: [
                  Expanded(
                    child: Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 10.0),
                      child: TextField(
                        controller: _codeTextController,
                        onChanged: (v) {
                          _checkRegisterEnable();
                        },
                        maxLength: 4,
                        decoration: const InputDecoration(
                            counterText: "",
                            hintText: "请输入验证码",
                            hintStyle: TextStyle(
                              color: Color(0xFF969696),
                            ),
                            border: InputBorder.none),
                        keyboardType: TextInputType.number,
                        inputFormatters: [
                          FilteringTextInputFormatter.digitsOnly, //数字，只能是整数
                        ],
                        maxLines: 1,
                      ),
                    ),
                  ),
                  const SizedBox(width: 6),
                  Container(
                    child: TextButton(
                      onPressed: () {
                        // 处理按钮点击事件
                        // 这里可以放置发送验证码的逻辑
                        _isCodeButtonDisabled ? null : _sendCode();
                      },
                      style: ButtonStyle(
                        backgroundColor: MaterialStateProperty.all(
                            _isCodeButtonDisabled ? Colors.grey : Colors.blue),
                        foregroundColor: MaterialStateProperty.all(Colors.white),
                        shape: MaterialStateProperty.all(
                          const RoundedRectangleBorder(
                            borderRadius: BorderRadius.all(Radius.circular(30)),
                          ),
                        ),
                      ),
                      child: Text(_isCodeButtonDisabled ? "$_codeCountdownSeconds" : '发送验证码'),
                    ),
                  ),
                  const SizedBox(width: 10)
                ],
              ),
            ),

            const SizedBox(height: 20),
            const Align(
              alignment: Alignment.center,
              child: Text(
                "未注册的手机号验证通过后将自动注册",
                style: TextStyle(color: Color(0xFF969696), fontSize: 12),
              ),
            ),
            const SizedBox(height: 20),
            //登录按钮
            GestureDetector(
              // onTap: _login,
              onTap: _loginEnable ? () => _login() : null,
              child: Container(
                height: 50,
                padding: const EdgeInsets.symmetric(vertical: 10),
                decoration: BoxDecoration(
                  //圆角半径
                  borderRadius: const BorderRadius.all(Radius.circular(50.0)),
                  color: _loginEnable ? const Color(0xFF2A6FE5) : const Color(0xFF80A3DF),
                  // color: Color(0xFF2A6FE5),
                ),
                child: const Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(
                      "登录",
                      style:
                          TextStyle(fontSize: 18, color: Colors.white, fontWeight: FontWeight.bold),
                    ),
                  ],
                ),
              ),
            ),
            const SizedBox(height: 12),
            // 注册账号/忘记密码
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                GestureDetector(
                  onTap: _pwdLogin,
                  child: const Text(
                    "密码登录",
                    style: TextStyle(color: Color(0xFF3075E9), fontWeight: FontWeight.bold),
                  ),
                ),
                GestureDetector(
                  onTap: _forgetPwd,
                  child: const Text(
                    "忘记密码",
                    style: TextStyle(color: Color(0xFF3075E9), fontWeight: FontWeight.bold),
                  ),
                ),
              ],
            ),
            const Expanded(child: SizedBox()),
            Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                //复选框
                SizedBox(
                  width: 20,
                  height: 20,
                  child: Checkbox(
                    value: _checked,
                    onChanged: (v) => setState(() {
                      _checked = v!;
                      _checkRegisterEnable();
                    }),
                    checkColor: const Color(0xFFFFFFFF),
                    activeColor: const Color(0xFF2067DF),
                    // visualDensity: VisualDensity(horizontal: 20, vertical: 20),
                  ),
                ),
                const SizedBox(width: 10),
                //声明信息
                Expanded(
                  child: RichText(
                    // softWrap: true, // 让文字自动换行
                    text: TextSpan(
                      children: [
                        const TextSpan(
                            text: "我已阅读并同意",
                            style: TextStyle(fontSize: 16, color: Color(0xFF969696))),
                        TextSpan(
                          text: "软件许可及服务协议",
                          style: const TextStyle(fontSize: 16, color: Color(0xFF2E73E8)),
                          recognizer: TapGestureRecognizer()
                            ..onTap = () {
                              // 在此处添加要执行的操作
                              print('点击了 软件许可及服务协议');
                            },
                        ),
                        const TextSpan(
                            text: "和", style: TextStyle(fontSize: 16, color: Color(0xFF969696))),
                        TextSpan(
                          text: "隐私政策",
                          style: const TextStyle(fontSize: 16, color: Color(0xFF2E73E8)),
                          recognizer: TapGestureRecognizer()
                            ..onTap = () {
                              // 在此处添加要执行的操作
                              print('点击了 隐私政策');
                            },
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),

            const SizedBox(height: 20),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Expanded(
                  child: Container(
                    height: 0.5,
                    color: const Color(0xFFB3C6DB), // 横线颜色
                  ),
                ),
                const SizedBox(width: 10),
                const Text("第三方登录", style: TextStyle(color: Color(0xFFB3C6DB))),
                const SizedBox(width: 10),
                Expanded(
                  child: Container(
                    height: 0.5,
                    color: const Color(0xFFB3C6DB), // 横线颜色
                  ),
                ),
              ],
            ),
            const SizedBox(height: 20),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                GestureDetector(
                    onTap: _wechat,
                    child: Image.asset(ICON_THIRD_LOGIN_WECHAT, width: iconSize, height: iconSize)),
                const SizedBox(width: 20),
                GestureDetector(
                  onTap: _qq,
                  child: Image.asset(ICON_THIRD_LOGIN_QQ, width: iconSize, height: iconSize),
                ),
                const SizedBox(width: 20),
                GestureDetector(
                  onTap: _x,
                  child: Image.asset(ICON_THIRD_LOGIN_X, width: iconSize, height: iconSize),
                ),
              ],
            ),
            const SizedBox(height: 60),
          ],
        ),
      ),
    );
  }

  @override
  void dispose() {
    _phoneTextController.dispose();
    super.dispose();
  }

  _forgetPwd() {
    Get.toNamed(Routes.forgotPasswordPage);
  }

  _checkRegisterEnable() {
    if (_phoneTextController.text.isEmpty || _codeTextController.text.length != 4 || !_checked) {
      setState(() {
        _loginEnable = false;
      });
    } else {
      setState(() {
        _loginEnable = true;
      });
    }
  }

  _sendCode() async {
    Log.d("发送验证码");
    if (_phoneTextController.text.isEmpty) {
      Log.d("手机号码不能为空");
      return;
    }

    setState(() {
      _isCodeButtonDisabled = true;
      _codeCountdownSeconds = 60; // 重置倒计时
    });
    var dio = HttpUtil.instance?.serviceDio();
    dio.options.headers['tenant-id'] = "1";
    Map<String, dynamic> data = {
      'mobile': _phoneTextController.text,
      'scene': 1,
    };
    Resp.Response response = await dio.post("/member/auth/send-sms-code", data: data);
    print("验证码 ： $response"); //成功： {"code":0,"data":true,"msg":""}
    try {
      Map<String, dynamic> smsCodeMap = jsonDecode(response.toString());
      SmsCodeBean smsCodeBean = SmsCodeBean.fromJson(smsCodeMap);
      if (smsCodeBean.code == 0) {
        SmartDialog.showToast("短信发送成功");
      } else {
        SmartDialog.showToast(smsCodeBean.msg ?? "短信发送失败");
      }
    } catch (e) {
      print("e: $e");
    }
    _startCountdownTimer();
  }

  _startCountdownTimer() {
    Log.d("验证码计时器");
    _codeCountdownTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
      setState(() {
        if (_codeCountdownSeconds > 1) {
          _codeCountdownSeconds--;
        } else {
          _codeCountdownTimer.cancel();
          _isCodeButtonDisabled = false; // 计时结束后重新启用按钮
        }
      });
    });
  }

  _checkPwdIsValid(String s) {
    // setState(() {
    //   _pwdValid = _passwordRegex.hasMatch(s);
    // });
  }

  ///登录
  _login() async {
    SmartDialog.showLoading(msg: "请稍后...", clickMaskDismiss: false, backDismiss: false);
    SharedPreferences prefs = await SharedPreferences.getInstance();
    var dio = HttpUtil.instance?.serviceDio();
    dio.options.headers['tenant-id'] = "1";
    Map<String, dynamic> data = {
      'mobile': _phoneTextController.text,
      'code': _codeTextController.text,
    };
    Resp.Response response = await dio.post("/member/auth/sms-login", data: data);
    print("登录结果 ： $response");
    try {
      Map<String, dynamic> loginMap = jsonDecode(response.toString());
      LoginBean loginBean = LoginBean.fromJson(loginMap);

      if (loginBean.code == 0) {
        //登录成功
        prefs.setInt(SP_USER_ID, loginBean.data?.userId ?? -1);
        prefs.setString(SP_ACCESS_TOKEN, loginBean.data?.accessToken ?? "");
        prefs.setString(SP_REFRESH_TOKEN, loginBean.data?.refreshToken ?? "");

        Get.offAllNamed(Routes.initial);
      } else {
        SmartDialog.showToast(loginBean.msg ?? "登录失败");
      }
    } catch (e) {
      print("e: $e");
    } finally {
      SmartDialog.dismiss(status: SmartStatus.loading);
    }
  }

  _pwdLogin() {
    Get.toNamed(Routes.pwdLoginPage);
  }

  _wechat() {
    SmartDialog.showToast("微信登录");
    Log.d("微信");
  }

  _qq() {
    SmartDialog.showToast("QQ登录");
    Log.d("QQ");
  }

  _x() {
    SmartDialog.showToast("推特登录");
    Log.d("推特");
  }
}
